﻿Partial Public Class DocTemplateExplorer

    Public Overridable Sub TreeActionOptionListLoad()
        Me.MetaControlTreeListActionOptionList.Add(New ActionOption("SpecRoot", "ACT_XXXXX", "Copy to new Revision", AddressOf CopyToNewRevision, True, True))
    End Sub

    Public Sub GridActionOptionListLoad(sender As Object, e As EventArgs)
        Dim x As GridExtPL = TryCast(sender, GridExtPL)
        Dim action As ActionOption = New ActionOption("DocTemplate1", "ACT_00184", "Open in Document Designer", AddressOf MenuOpenInDocumentDesigner, True, True)
        x.GridActionOptionList.Add(action)
        action = New ActionOption("DocTemplate1", "ACT_00177", "Open in Report Designer", AddressOf MenuOpenInDesignerDocumentTemplate, True, True)
        x.GridActionOptionList.Add(action)
        action = New ActionOption("DocTemplate", "ACT_00050", "Export Document Template", AddressOf MenuExportDocumentTemplate, True, True)
        x.GridActionOptionList.Add(action)
        action = New ActionOption("DocTemplate", "ACT_00051", "Import Document Template", AddressOf MenuImportDocumentTemplate, True, True)
        x.GridActionOptionList.Add(action)
        action = New ActionOption("DocTemplate", "ACT_00052", "Export Document Template To " + AppManager.ExportToMasterDB, AddressOf MenuExportDocumentTemplateToMaster, True, True)
        x.GridActionOptionList.Add(action)
        action = New ActionOption("DocTemplateCopy", "ACT_xxxxx", "Copy Document Template", AddressOf CopyDocumentTemplate, True, True)
        x.GridActionOptionList.Add(action)

        'action = New ActionOption("DocTemplateRevision", "ACT_xxxxx", "Copy to new revision", AddressOf MenuExportDocumentTemplateToMaster, True, 1)
        'x.GridActionOptionList.Add(action)
    End Sub

    Public Overridable Sub DocumentTemplate_ContextMenuBeforePopup(sender As Object, e As EventArgs)
        'Dim aMenu As GridViewMenu = CType(sender, GridViewMenu)
        'Dim row As DataRow = aMenu.View.GetFocusedDataRow()

        'If row IsNot Nothing Then
        '    Dim i As Integer = 0
        '    'For Each item In aMenu.Items
        '    While i < aMenu.Items.Count
        '       OUTSTANDINGISSUE: on se base sur le Caption pour retracer une action dans la liste des Items du Menu, mais ce caption peut changer a tout moment et invalider la logique du code. clieng 2014-04-24.
        '        If aMenu.Items(i).Caption.Contains("Open in Report Designer") Then

        '            If row.Table.Columns.Contains("TypeId_FK") AndAlso Not IsDBNull(row("TypeId_FK")) Then
        '                If Guid.Parse(row("TypeId_FK").ToString) = IdRepository.APP_DOCTEMPLATETYPE_DOC Then
        '                    aMenu.Items(i).Enabled = False
        '                End If

        '            End If
        '        End If
        '        Open with Document Designer
        '        If aMenu.Items(i).Caption.Contains("Open in Document Designer") Then

        '            If row.Table.Columns.Contains("TypeId_FK") AndAlso Not IsDBNull(row("TypeId_FK")) Then
        '                If Guid.Parse(row("TypeId_FK").ToString) = IdRepository.APP_DOCTEMPLATETYPE_REPX Then
        '                    aMenu.Items(i).Enabled = False
        '                End If

        '            End If
        '        End If

        '        i += 1
        '    End While
        'End If
    End Sub

    Private Sub MenuExportDocumentTemplate(ByVal sender As System.Object, ByVal e As EventArgs)
        Dim aDataRow As DataRow = CType(CType(sender, DXMenuItem).Tag, DataRow)
        Dim stringID As Guid
        Using aFile As New System.Windows.Forms.SaveFileDialog
            aFile.DefaultExt = "xml"
            aFile.FileName = "DocTemplate_" + aDataRow("DocumentTemplateCD").ToString + "_" + aDataRow("Name").ToString
            If aFile.ShowDialog() = DialogResult.OK Then
                stringID = New Guid(aDataRow("DocumentTemplateId").ToString)
                If DocumentTemplate_PL.ExportDocTemplate(aFile.FileName, stringID) Then
                    MessageWindow.ShowMessage("Export Document Template successful", MsgBoxStyle.Information)
                End If
            End If
        End Using

    End Sub

    Private Sub MenuOpenInDocumentDesigner(ByVal sender As Object, ByVal e As EventArgs)
        Me.Cursor = Cursors.WaitCursor
        Dim aDataRow As DataRow = CType(CType(sender, DXMenuItem).Tag, DataRow)

        If aDataRow IsNot Nothing Then
            Dim newForm As DocGen = New DocGen With {.MdiParent = Me.ParentForm, .Name = aDataRow("DocumentTemplateId").ToString, .Text = String.Format("Designing Document : {0}", aDataRow("Name").ToString), .ShowIcon = True}
            newForm.DocumentTemplateID = CType(aDataRow("DocumentTemplateId"), Guid)
            newForm.Show()
        End If

        Me.Cursor = Cursors.Default
    End Sub

    Private Sub MenuOpenInDesignerDocumentTemplate(ByVal sender As System.Object, ByVal e As EventArgs)
        Me.Cursor = Cursors.WaitCursor
        Dim aDataRow As DataRow = CType(CType(sender, DXMenuItem).Tag, DataRow)

        If aDataRow IsNot Nothing Then
            Dim queryID As Guid
            If IsDBNull(aDataRow("QueryID_FK")) Then
                queryID = Nothing
            Else
                queryID = Guid.Parse(aDataRow("QueryID_FK").ToString)
            End If

            Dim newForm As ReportBuilder = New ReportBuilder With {.Name = aDataRow("DocumentTemplateId").ToString, .Text = String.Format("Designing Report : {0}", aDataRow("Name").ToString), .ShowIcon = True}
            Dim aMyXtraReport As MyXtraReport = New MyXtraReport()
            aMyXtraReport.DocumentTemplateID = Guid.Parse(aDataRow("DocumentTemplateId").ToString)
            aMyXtraReport.DocumentTemplateName = aDataRow("Name").ToString
            aMyXtraReport.QueryID_FK = queryID

            newForm.aMyXtraReport = aMyXtraReport

            newForm.Show()
        End If

        Me.Cursor = Cursors.Default
    End Sub

    Private Sub MenuImportDocumentTemplate(ByVal sender As System.Object, ByVal e As EventArgs)
        Dim saved As Boolean
        Using aFile As New System.Windows.Forms.OpenFileDialog
            aFile.FileName = "*.xml"
            aFile.DefaultExt = "xml"
            aFile.Multiselect = True
            If aFile.ShowDialog() = DialogResult.OK Then
                For Each file As String In aFile.FileNames
                    saved = DocumentTemplate_PL.ImportMetaDocTemplate(file)
                Next
                If saved Then
                    MessageWindow.ShowMessage("Import Document Template successful", MsgBoxStyle.Information)
                End If
            End If
        End Using
    End Sub

    Private Sub CopyDocumentTemplate(ByVal sender As Object, ByVal e As EventArgs)
        Try
            Dim dataFormat As Guid
            Dim binaryString() As Byte
            Dim template() As Byte = Nothing
            Dim sqlcmd As SqlClient.SqlCommand = Nothing
            Dim aDataRow As DataRow = CType(CType(sender, DXMenuItem).Tag, DataRow)
            Dim reportName As String = aDataRow("Name").ToString
            Dim reportID As String = aDataRow("DocumentTemplateId").ToString

            Using mqReport As MetaQuery = MetaQuery.GetMetaQueryByName("ReadReportFromDocTemplate")
                mqReport.SQLWhere = String.Format("Name = '{0}' ", reportName)
                mqReport.FillResultQuery()
                '
                If mqReport.ResultQuery.Rows.Count = 1 Then

                    If mqReport.ResultQuery.Rows(0).Item("BinaryData") IsNot DBNull.Value Then
                        binaryString = CType(mqReport.ResultQuery.Rows(0).Item("BinaryData"), Byte())
                        dataFormat = DirectCast(mqReport.ResultQuery.Rows(0).Item("DataFormatId_FK"), Guid)

                        If Not dataFormat = Nothing AndAlso dataFormat = IdRepository.APP_DATAFORMAT_UTF8 Then
                            template = LoadDocument_UsingUTF8(binaryString, reportName)
                        End If

                        Try
                            sqlcmd = MetaQuery.GetSPCmdByMetaName("DocumentTemplate_Copy")
                            sqlcmd.Parameters("@FromDocumentTemplateId").Value = Guid.Parse(reportID)
                            sqlcmd.Parameters("@ReportName").Value = "Copy_of_" + reportName
                            sqlcmd.Parameters("@ReportBinaryData").Value = template

                            sqlcmd.ExecuteReader(CommandBehavior.CloseConnection)

                            ReloadTree()
                        Catch ex As Exception
                            MessageWindow.ShowMessage(ex)

                        Finally
                            If sqlcmd IsNot Nothing Then
                                sqlcmd.Connection.Close()
                                sqlcmd.Dispose()
                            End If
                        End Try
                    End If
                End If
            End Using

        Catch ex As Exception
            MessageWindow.ShowMessage(ex)
        End Try
    End Sub

    Private Sub MenuExportDocumentTemplateToMaster(ByVal sender As System.Object, ByVal e As EventArgs)

        Dim aDataRow As DataRow = CType(CType(sender, DXMenuItem).Tag, DataRow)
        Dim controlID As Guid

        controlID = New Guid(aDataRow("DocumentTemplateId").ToString)
        If DocumentTemplate_PL.ExportDocTemplateToMaster(controlID) Then
            MessageWindow.ShowMessage("Export Document Template Successful", MsgBoxStyle.Information)
        End If
    End Sub


    Private Function LoadDocument_UsingUTF8(ByVal binaryString() As Byte, ByVal reportName As String) As Byte()
        Dim reportString As String
        Dim report As XtraReport = Nothing
        Dim data() As Byte
        Dim encoder As UTF8Encoding

        Try
            encoder = New UTF8Encoding()
            '
            reportString = Encoding.UTF8.GetString(binaryString)
            reportString = reportString.Replace(reportName, "Copy_of_" + reportName)
            '
            data = encoder.GetBytes(reportString)
        Catch ex As Exception
            Throw ex
        End Try

        Return data
    End Function



    Private Sub CopyToNewRevision(ByVal sender As Object, ByVal e As EventArgs)
        Try
            If NodeDataRow IsNot Nothing Then
                If NodeDataRow.Table.Columns.Contains("KeyID") Then
                    If DocumentTemplate_PL.CopyToNewRevision(DirectCast(NodeDataRow("KeyID"), Guid)) Then
                        MessageWindow.ShowMessage("Document was succesfully copied.") 'DeskTopManager.GetMessage("MetaStringCd")
                    Else
                        MessageWindow.ShowMessage("Document wasn't copied.")
                    End If
                Else
                    MessageWindow.ShowMessage("Column KeyID does not exist")
                End If
            End If
        Catch ex As Exception
            MessageWindow.ShowMessage(ex)
        End Try
    End Sub

End Class


